<template>
  <div class="container">
    <van-nav-bar :title="title" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <van-button class="saveBtn" type="primary" native-type="submit" @click="handleSubmit()">提交</van-button>
    <div class="publicBox formDivBox">
      <van-form ref="form">
        <van-field name="applyNo" v-model="ruleForm.applyNo" label="申请单号" :disabled="haveCodeRule" :rules="[{ required: haveCodeRule === true ? false : true, message: '请输入申请单号', trigger: 'blur' }]" size="mini" />

        <van-field readonly clickable placeholder="请选择" name="faultClassifyName" v-model="ruleForm.faultClassifyName" label="故障分类" @click="showFaultClassfy = true" :rules="[{ required: true, message: '请选择故障分类', trigger: 'blur' }]" />

        <van-field readonly clickable placeholder="请选择" name="equipCode" v-model="ruleForm.equipCode" label="设备编码" @click="showEq = true" :rules="[{ required: true, message: '请选择设备', trigger: 'blur' }]" />
        <!-- 
       <van-field  clickable placeholder="请选择" name="equipCode" v-model="ruleForm.equipCode"   
        label="设备编码" @click="showEq = true" :rules="[{ required: true, message: '请选择设备', trigger: 'blur' }]" />
   
 -->

        <van-field label="设备名称" :value="ruleForm.equipName" readonly size="mini" />
        <van-field label="故障发生时间" name="faultTime" :rules="[{ required: true, message: '请选择故障发生时间', trigger: 'blur' }]" v-model="ruleForm.faultTime" size="mini" readonly @click="showTime = true" />
        <van-field readonly clickable placeholder="请选择" name="applyName" v-model="ruleForm.applyName" label="申请人" @click="showUser = true" :rules="[{ required: true, message: '请选择申请人', trigger: 'blur' }]" />
        <van-field name="emergency" label="紧急度" :rules="[{ required: true, message: '请选择紧急度', trigger: 'blur' }]">
          <template #input>
            <van-radio-group v-model="ruleForm.emergency" direction="horizontal">
              <van-radio name="低">低</van-radio>
              <van-radio name="中">中</van-radio>
              <van-radio name="高">高</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field label="所属部门" :value="ruleForm.factoryName" readonly size="mini" />
        <van-field v-model="ruleForm.faultRemark" label="故障描述" rows="2" size="mini" type="textarea" maxlength="200" show-word-limit />
        <van-field name="repairMethod" label="维修方式" :rules="[{ required: true, message: '请选择维修方式', trigger: 'blur' }]">
          <template #input>
            <van-radio-group v-model="ruleForm.repairMethod" direction="horizontal">
              <van-radio :name="1">内修</van-radio>
              <van-radio :name="2">外修</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <!-- v-if="this.detailsObj.repairMethod === 1" -->
        <van-field readonly v-if="this.ruleForm.repairMethod === 1" clickable placeholder="请选择" name="groupName" v-model="ruleForm.groupName" label="班组" @click="showGroup = true" :rules="[{ required: true, message: '请选择班组', trigger: 'blur' }]" />

        <van-field-checkbox label="责任人" v-if="this.ruleForm.repairMethod === 1" v-model="userLists" placeholder="请选择" :columns="userListAll" :option="{label:'userName',value:'userId'}" :rules="[{ required: true, message: '请选择责任人', trigger: 'blur' }]" />
        <van-button v-if="this.ruleForm.repairMethod === 1" @click="selectAll">全选</van-button>
        <van-button v-if="this.ruleForm.repairMethod === 1" @click="selectNone">全不选</van-button>

        <van-field label="期望解决时间" name="expectedResolutionTime" v-model="ruleForm.expectedResolutionTime" size="mini" readonly @click="showQwTime = true" />

        <van-field v-if="this.ruleForm.repairMethod === 2" v-model="ruleForm.repairOutReason" label="外修理由" :rules="[{ required: ruleForm.repairMethod === 1 ? false : true, message: '请输入外修理由', trigger: 'blur' }]" :disabled="ruleForm.repairMethod === 1 ? true : false" rows="2" size="mini" type="textarea" maxlength="200" show-word-limit />

        <van-field readonly clickable v-if="this.ruleForm.repairMethod === 2" placeholder="请选择" name="companyName" v-model="ruleForm.companyName" label="维保商" @click="showMaintainDealer = true" :rules="[{ required: true, message: '请选择维保商', trigger: 'blur' }]" />

        <!-- 维保商 -->
        <van-popup v-show="ruleForm.repairMethod === 2" v-model="showMaintainDealer" position="bottom">
          <van-picker title="维保商" show-toolbar :columns="maintainerData" @confirm="onMaintainerData" @cancel="showMaintainDealer = false" />
        </van-popup>
        <p class="pStyle">自定义字段</p>
        <div class="extensionDiv">
          <van-field v-for="(item, index)  in extension" :key="index" placeholder="请输入" v-model="item.value" :name="item.value" :label="item.fieldName" />
        </div>
      </van-form>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>

    <!--  时间选择 -->
    <van-popup v-model="showQwTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeQwChange" @cancel="showQwTime = false" />
    </van-popup>
    <!-- 故障分类 -->
    <van-popup v-model="showFaultClassfy" position="bottom">
      <van-picker title="故障分类" show-toolbar :columns="faultClassData" @confirm="onFaultClassfy" @cancel="showFaultClassfy = false" />
    </van-popup>
    <!-- 班组选择 -->
    <van-popup v-model="showGroup" position="bottom">
      <van-picker title="班组选择" show-toolbar :columns="getGroupList" @confirm="onGroup" @cancel="showGroup = false" />
    </van-popup>
    <!-- 人员 -->
    <van-popup v-model="showUser" position="bottom">
      <van-picker title="人员选择" show-toolbar :columns="userInfo" @confirm="chooseUser" @cancel="showUser = false" />
    </van-popup>
    <!-- 设备 -->
    <van-popup v-model="showEq" position="top" class="search-popup">
      <div class="search-header">
        <van-search v-model="searchKeyword" placeholder="搜索设备" @input="onSearch" @clear="onClear" />
      </div>
      <van-list v-model="loading" :finished="finished" @load="onLoad">
        <van-cell v-for="(item, index) in filteredEqCodeData" :key="item.equipCode" @click="onSelect(item)" class="list-item">
          {{ item.equipCode }}
        </van-cell>
      </van-list>
      <!-- 这里可以保留原来的picker作为备用或替换方案 -->
      <!-- <van-picker title="设备" show-toolbar :columns="filteredEqCodeData" @confirm="onEq" @cancel="showEq = false" /> -->
    </van-popup>
  </div>
</template>
<script>
import { myFunction } from '@/utils/function'
import vanFieldCheckbox from '@/components/selectUser'
// import _ from 'lodash'
export default {
  name: 'RepairRequest',
  components: { vanFieldCheckbox },
  data () {
    return {
      title: '',
      haveCodeRule: false,
      currentDate: new Date(),
      userListAll: [],
      userList: [],
      userLists: [],
      // repairMethod:1,
      ruleForm: {
        applyNo: '',
        equipId: '',
        equipName: '',
        equipCode: '',
        factoryId: '',
        groupId: '', // 班组
        groupName: '',
        maintainDealerId: '', // 维保商主键
        expectedResolutionTime: '',
        companyName: '',
        factoryName: '',
        classifyName: '',
        repairMethod: 1,
        faultClassifyId: '',
        faultClassifyName: '',
        faultTime: '',
        applyName: JSON.parse(localStorage.getItem('padUserInfo')).data
          .userName,
        applyBy: JSON.parse(localStorage.getItem('padUserInfo')).data.userId,
        id: '',
        userList: [],
        emergency: '低'
      },
      show: false,
      code: localStorage.getItem('code'),
      search: {
        current: 1,
        size: 5
      },
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      showTime: false,
      showQwTime: false,
      showUser: false,
      showClassfy: false,
      userInfo: [],
      userInfos: [],
      showEq: false,
      showGroup: false,
      showMaintainDealer: false,
      eqCodeData: [],
      eqCodeDatas: [],
      showFaultClassfy: false,
      faultClassData: [],
      faultClassDatas: [],
      maintainerData: [],
      maintainerDatas: [],
      getGroupList: [],
      getGroupLists: [],
      extension: [],
      searchKeyword: '',
      filteredEqCodeData: [],
      loading: false,
      finished: false,
      tableName: 't_equip_repair_order' // 自定义字段所属表名
    }
  },

  watch: {
  },
  created () {

  },
  mounted () {
    this.getData()
  },
  methods: {
    formatter (value) {
      return value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
    },
    async getData () {
      this.detailsObj = this.$store.state.data
      this.title = '新增'
      await this.getRuleIsOpen()
      await this.getEqCode()
      await this.getfaultClass()
      await this.getAllUser()
      await this.getGroupInfo()
      if (this.detailsObj.equipId !== null && this.detailsObj.equipId !== '' && this.detailsObj.equipId !== undefined)
        await this.getMaintainer(this.detailsObj.equipId)
      else
        await this.getMaintainer(0)
      setTimeout(async () => {
        if (this.detailsObj)
          this.ruleForm = { ...this.ruleForm, ...this.detailsObj }
        const res = await this.$axios.get(
          `/dobo-platform/general/field/extension/${this.tableName}`
        )
        if (res && res.data.code === 200) {
          this.extension = res.data.data
          if (this.extension.length > 0) {
            this.extension.forEach((el) => {
              for (const key in this.detailsObj) {
                if (Object.hasOwnProperty.call(this.detailsObj, key)) {
                  const item = this.detailsObj[key]
                  if (el.fieldColumn === key) {
                    el.value = item
                  }
                }
              }
            })
          }
        }
        /* 默认为系统当前时间 */
        this.ruleForm.faultTime = myFunction(new Date()).slice(0, 16)
      })
    },
    /* 维修单号是否自动生成 */
    async getRuleIsOpen () {
      this.loading = true
      const res = await this.$axios.get('/dobo-equip/repair/order/ruleIsOpen')
      if (res.data.code === 200 && res.data.data === true) {
        this.haveCodeRule = true
        setTimeout(() => {
          this.loading = false
        }, 300)
      } else {
        this.haveCodeRule = false
        setTimeout(() => {
          this.loading = false
        }, 300)
      }
    },
    // 全选  
    selectAll () {
      this.userLists = this.userListAll.map(item => item.userId)
      // 如果需要，也可以设置 isSelectAll 为 true  
      // 但在这个简单的例子中，我们直接操作 userLists  
    },
    // 全不选  
    selectNone () {
      this.userLists = []
      // 如果需要，也可以设置 isSelectAll 为 false  
      // 但同样，在这个例子中，我们直接操作 userLists  
    },

    /* 获取全部设备 */
    async getEqCode () {
      const res = await this.$axios.get(
        `/dobo-equip/repair/order/getPermissionsEquip`
      )
      if (res.data.code === 200) {
        this.eqCodeData = res.data.data

        //  res.data.data.forEach((item) => {
        //     this.eqCodeData.push(item.equipCode)
        //  })
      }
    },

    onSearch (value) {
      this.searchKeyword = value
      this.fetchData(this.searchKeyword)
    },
    onClear () {
      this.searchKeyword = ''
      this.fetchData(this.searchKeyword)
    },
    /*  async  fetchData(keyword) {  
      return new Promise(resolve => {  
        if (keyword === '') {  
          this.filteredEqCodeData = this.eqCodeData.map(item => ({  
            ...item,  
            equipCode: item.equipCode  
          })) 
          this.finished = true
        } else {  
          this.filteredEqCodeData = this.eqCodeData.filter(item =>  
            item.equipCode.includes(keyword)  
          ).map(item => ({  
            ...item,  
            equipCode: item.equipCode  
          }));  
          this.finished = this.filteredEqCodeData.length < this.eqCodeData.length
        }  
        this.loading = false 
        resolve() // 解决 Promise  
      }) 
    },*/

    fetchData (keyword) {
      if (keyword === '') {
        this.filteredEqCodeData = this.eqCodeData.map(item => ({
          ...item,
          equipCode: item.equipCode
        }))
        this.finished = true
      } else {
        this.filteredEqCodeData = this.eqCodeData.filter(item =>
          item.equipCode.includes(keyword)
        ).map(item => ({
          ...item,
          equipCode: item.equipCode
        }))
        this.finished = this.filteredEqCodeData.length < this.eqCodeData.length
      }
      this.loading = false
    },

    onSelect (item) {
      // 设置选择的设备信息  
      this.ruleForm.equipId = item.id
      this.ruleForm.equipCode = item.equipCode
      this.ruleForm.equipName = item.equipName
      this.ruleForm.factoryId = item.factoryId
      this.ruleForm.factoryName = item.factoryName
      this.showEq = false
    },
    // 加载更多数据（如果列表很长，需要分页处理）  
    onLoad () {
      if (!this.finished) {
        this.fetchData(this.searchKeyword)
        // 模拟加载更多  
        setTimeout(() => {
          // 假设有更多数据加载  
          this.loading = false
          // 这里只是示例，实际你应该从服务器获取更多数据  
          this.finished = true // 假设没有更多数据  
        }, 5000)
      }

    },
    /**  
        * 加载更多数据  
        */
    loadMore () {
      this.currentPage++
      this.getEqCode(this.currentPage)
    },

    /* 设备选择 */
    onEq (value) {

      const selectedItem = this.eqCodeData.find(item => item.equipCode === value)
      if (selectedItem) {
        this.ruleForm.equipId = selectedItem.id
        this.ruleForm.equipCode = selectedItem.equipCode
        this.ruleForm.equipName = selectedItem.equipName
        this.ruleForm.factoryId = selectedItem.factoryId
        this.ruleForm.factoryName = selectedItem.factoryName
      }
      this.showEq = false
    },
    /** 获取故障分类数据*/
    async getfaultClass () {
      const res = await this.$axios.get(
        '/dobo-equip/equip/fault/classify/getList',
        this.faultClassSearch
      )
      if (res?.data.code === 200) {
        this.faultClassDatas = res.data.data
        res.data.data.forEach((item) => {
          this.faultClassData.push(item.classifyName)
        })
      }
    },
    /* 故障分类选择 */
    onFaultClassfy (e) {
      this.faultClassDatas.forEach((item) => {
        if (item.classifyName === e) {
          this.ruleForm.faultClassifyId = item.id
          this.ruleForm.faultClassifyName = item.classifyName
          this.ruleForm.faultRemark = item.remark
        }
      })
      this.showFaultClassfy = false
    },
    /* 获取所有用户 */
    async getAllUser () {
      const res = await this.$axios.get('/dobo-user/user/getAllUser')
      if (res && res.data.code === 200) {
        this.userInfos = res.data.data
        res.data.data.forEach((item) => {
          this.userInfo.push(item.name)
        })
      }
    },
    /**  人员选择 */
    chooseUser (e) {
      this.userInfos.forEach((item) => {
        if (item.name === e) {
          this.ruleForm.applyBy = item.id
          this.ruleForm.applyName = item.name
        }
      })
      this.showUser = false
    },
    /* 时间选择赋值 */
    onTimeChange (value) {
      setTimeout(() => {
        this.ruleForm.faultTime = myFunction(value)

        this.showTime = false
      }, 500)
    },
    /* 时间选择赋值 */
    onTimeQwChange (value) {
      setTimeout(() => {
        this.ruleForm.expectedResolutionTime = myFunction(value)

        this.showQwTime = false
      }, 500)
    },
    /* 获取所有班组 */
    async getGroupInfo () {
      const res = await this.$axios.get(`/dobo-equip/repair/order/getGroup`)
      if (res && res.data.code === 200) {
        this.getGroupLists = res.data.data
        res.data.data.forEach((item) => {
          this.getGroupList.push(item.groupName)
        })
      }
    },
    /* 班组选择 */
    onGroup (e) {
      this.getGroupLists.forEach((item) => {
        if (item.groupName === e) {
          this.ruleForm.groupId = item.groupId
          this.ruleForm.groupName = item.groupName
          if (item.groupUsers) {
            this.userListAll = item.groupUsers
            //    item.groupUsers.forEach((item) => {
            //    this.userLists.push(item.userId)
            //    this.userList.push(item.userName)
            //  })
          }
        }
      })
      this.showGroup = false
    },
    /* 获取维保商 */
    async getMaintainer (equipId) {
      const res = await this.$axios.get(
        `/dobo-equip/repair/order/getMaintainDealerByEquip?equipId=${equipId}`
      )
      if (res?.data.code === 200) {
        this.maintainerDatas = res.data.data
        res.data.data.forEach((item) => {
          this.maintainerData.push(item.companyName)
        })
        /* 如果存在维修记录，则自动带出最近一次外修时对应的维保商（如果维保商已停用，则不带出） */
        this.maintainerData.forEach((item) => {
          if (item.isSelect === 1) {
            this.ruleForm.maintainDealerId = item.maintainDealerId
            this.ruleForm.companyName = item.companyName
          }
        })
      }
    },
    /* 维保商选择 */
    onMaintainerData (e) {
      this.maintainerDatas.forEach((item) => {
        if (item.companyName === e) {
          this.ruleForm.maintainDealerId = item.maintainDealerId
          this.ruleForm.companyName = item.companyName
        }
      })
      this.showMaintainDealer = false
    },


    handleSubmit () {
      this.$refs.form
        .validate()
        .then(() => {
          this.$dialog
            .confirm({
              title: '提示',
              message: '是否确认提交？'
            })
            .then(() => {
              this.submitApi()
            })
            .catch(() => {
              return false
            })
        })
        .catch(() => { })
    },
    submitApi () {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      /** 保存自定义字段 */
      if (this.extension.length > 0) {
        const obj = {}
        this.extension.filter((item, index) => {
          obj[item.fieldColumn] = item.value ? item.value : ''
        })
        this.ruleForm.extensionInfo = obj
      }
      this.ruleForm.faultTime = this.ruleForm.faultTime + ':00'
      let url = ''
      if (this.title === '编辑') {
        url = '/dobo-equip/repair/order/updateOrder'
      } else {
        url = '/dobo-equip/repair/order/insertOrder'
      }
      if (this.ruleForm.repairMethod == 1) {
        const list = []
        this.userListAll.forEach(item => {
          this.userLists.forEach(itx => {
            if (item.userId === itx) {
              list.push({ userId: item.userId, userName: item.userName }
              )
            }
          })
        })
        this.ruleForm.userList = list
      }
      this.$axios
        .post(url, this.ruleForm)
        .then((res) => {
          if (res.data.code === 200) {
            toast.clear()
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                this.$router.push('/eqRepairRequest')
              })
              .catch(() => { })
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              toast.clear()
              this.$router.push('/eqRepairRequest')
            }, 1000)
          }
        })
        .catch(() => { })
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/eqRepairRequest')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .inputRightFont {
    overflow: hidden;
    height: 40px;
    line-height: 40px;
    .sp {
      padding-left: 5px;
    }
  }
  .formDivBox {
    .van-field {
      border: 1px solid #f5f5f5;
    }
    .pStyle {
      height: 35px;
      line-height: 35px;
      background: #f5f5f5;
      text-align: center;
    }
    .extensionDiv {
      overflow: hidden;
      .van-field {
        width: 50%;
        float: left;
        border: 1px solid #f5f5f5;
      }
    }
  }
}
</style>
<style lang='scss'>
</style>
